package com.redis.springtest;

import com.redis.springtest.config.RedisConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import redis.clients.jedis.Jedis;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author Administrator
 * @create 2020-07-28 12:23
 */
public class AppRedisLua2 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisConnectionFactory jedisConnectionFactory = ctx.getBean("jedisConnectionFactory", RedisConnectionFactory.class);
        RedisConnection connection = jedisConnectionFactory.getConnection();
        Jedis jedis = (Jedis) connection.getNativeConnection();

        // 读入文件流
        byte[] bytes = readFileToByte("test.lua");
        // 发送二进制文件给redis
        byte[] sha1 = jedis.scriptLoad(bytes);
        // 使用返回标识符执行，其中第二个参数2，表示使用2个键
        // 后面的字符串都转换成二进制字节进行传输
        Object evalsha = jedis.evalsha(sha1, 2, "key1".getBytes(), "key2".getBytes(), "2".getBytes(), "4".getBytes());
        System.out.println(evalsha);
    }

    /**
     * Read file to byte byte [ ].
     *
     * @param file the file
     * @return the byte [ ]
     */
    private static byte[] readFileToByte(String file) {
        InputStream inputStream = AppRedisLua2.class.getClassLoader().getResourceAsStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int count = 0;
        try {
            while ((count = inputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();

    }
}
